$(function() {
	$("#drowdown").click(function() {
		if (!isDropDown) {
			isDropDown = true;
			$("#custom_search_panel").slideDown();
		} else {
			isDropDown = false;
			$("#custom_search_panel").slideUp();
		}

	});
	
	var http = new XMLHttpRequest;
	http.open("HEAD", ".", false);
	http.send(null);
	var today = new Date(http.getResponseHeader("Date"));
	var year_today = today.getFullYear();
	var month_today = (today.getMonth() + 1) < 10 ? "0" + (today.getMonth() + 1) : (today.getMonth() + 1);
	var date = year_today + '-' + month_today;
	var month_next = (month_today + 1) > 12 ? 1 : (month_today = 1);
	var year_next = (month_today + 1) > 12 ? (year_today + 1) : year_today;
	var date_next = year_next + '-' + month_next;
	//checkId 全选与反选
	$('table th input:checkbox').on('click', function() {
		var that = this;
		$(this).closest('table').find('tr > td:first-child input:checkbox')
			.each(function() {
				this.checked = that.checked;
			});
	});
	var isDropDown = false;
	var keywords = {};
	

	$("#pageSize").change(function() {
		var key = document.getElementById("keyword").value;
		dataPage(1, key,"");
	});
	

	$("#search_check_depar").click(function() {
		$("#keyword_content").empty();
		$("#keyword_content").append("<input id='chooseDeptID'  type='hidden'><input id='chooseDept' class='group_right search_input' type='text' style='width:300px'>");
	});
	$("#search_check_entry").click(function() {
		$("#keyword_content").empty();
		$("#keyword_content").append("<input id='from' class='date-picker search_date' name='searchDate'  type='text' data-date-format='yyyy-mm-dd' readonly='true'> 至 <input id='to' class='date-picker search_date' name='searchDate' type='text' data-date-format='yyyy-mm-dd' readonly='true'>");
		$("input[name='searchDate']").datepicker({
			autoclose: true,
			todayBtn: true
		});
	});
	$("#search_check_departure").click(function() {
		$("#keyword_content").empty();
		$("#keyword_content").append("<input id='from' class='date-picker search_date' name='searchDate'  type='text' data-date-format='yyyy-mm-dd' readonly='true'> 至 <input id='to' class='date-picker search_date' name='searchDate' type='text' data-date-format='yyyy-mm-dd' readonly='true'>");
		$("input[name='searchDate']").datepicker({
			autoclose: true,
			todayBtn: true
		});
	});
	$("#removeBtn").click(function() {
		$("#custom_search_panel").slideUp();
		isDropDown = false;
	});

	$("#chooseDept").click(function() {
		$("#chooseOrg").empty();
		$("#showOrgs").modal("show");
		$("#chooseOrg").ligerTree({
			url: '/api/organizations/getOrgTree?_t=' + new Date().getTime(),
			method: 'get',
			checkbox: false,
			nodeWidth: 120,
			idFieldName: "id",
			parentIDFieldName: 'pid',
			slide: false,
			onClick: function(node) {
				actionNodeID = node.data.id;
				getParentList(actionNodeID);
				// $.ajax({
				// 	url: '/api/organizations/getParents/' + actionNodeID,
				// 	type: 'get',
				// 	success: function(result) {
				// 		var parentString = "";
				// 		for (var i = result.length - 1; i >= 0; i--) {
				// 			if (i != 0) {
				// 				parentString += result[i].orgName + "/";
				// 			} else {
				// 				parentString += result[i].orgName;
				// 			}
				// 		}
				// 		if (result[0].orgType == "C") {
				// 			alert("请选择部门");
				// 		} else {
				// 			$("#chooseDept").val(parentString);
				// 			$("#chooseDeptID").val(result[0].id);
				// 			$("#showOrgs").modal('hide');
				// 		}
				// 	}
				// });

			}
		});
	});
    
    var getParentList = function(actionNodeID) {
    	$.ajax({
    		url: '/api/organizations/getParents/' + actionNodeID,
    		type: 'get',
    		success: function(result) {
    			var parentString = "";
    			for (var i = result.length - 1; i >= 0; i--) {
    				if (i != 0) {
    					parentString += result[i].orgName + "/";
    				} else {
    					parentString += result[i].orgName;
    				}
    			}
    			if (result[0].orgType == "C") {
    				alert("请选择部门");
    			} else {
    				$("#chooseDept").val(parentString);
    				$("#chooseDeptID").val(result[0].id);
    				$("#showOrgs").modal('hide');
    			}
    		}
    	});
    };

    //搜索输入框回车事件
    $("#keyword").keydown(function(e) {
    	if(e.keyCode == 13) {
    		$('#searchBtn').click();
    	}
    });
	
	$("#search_btn").click(function() {
		var keys = document.getElementsByName("search_key");
		var keywords = {};
		for (var i = 0; i < keys.length; i++) {
			if (keys[i].checked) {
				keywords.key = keys[i].value;
			}
		}
		if (keywords.key == 1) { //部门
			if ($("#chooseDeptID").val() != "") {
				keywords.value = $("#chooseDeptID").val();
			} else {
				bootbox.alert('请完善搜索信息！', function() {});
				return;
			}
		} else { //入职时间
			if ($("#from").val() != "" && $("#to").val() != "") {
				if ($("#from").val() > $("#to").val()) {
					bootbox.alert('开始时间不能大于结束时间！', function() {});
					return;
				} else {
					keywords.from = $("#from").val();
					keywords.to = $("#to").val();
				}
			} else {
				bootbox.alert('请完善搜索信息！', function() {});
				return;
			}
		}
		dataPage(1,"",JSON.stringify(keywords));
	});

	var dataPage = function(cpage, keyword,advancedKey) {
		// $('#staffBody').html("");
		var pageSize = $("#pageSize option:selected").text();
		$.ajax({
			url: '/api/employee?',
			type: 'get',
			data: {'pageSize':pageSize,'cpage':cpage,'keyword':keyword,'advancedKey':advancedKey, '_t':new Date().getTime()},
			success: function(data) {
				// console.info(data.count);
				// $("#showCount").html("共"+ data.count + "条记录");
				var udata = {};
				if (data == 'noPrivilege') {
					udata = {
						count: 0,
						data: []
					};
				} else {
					udata = data;
				}
				var page;
				if (udata.count < pageSize) {
					page = 1;
				} else {
					page = Math.ceil(udata.count / pageSize);
				}
				if(cpage == -1) {
					cpage = page;
				}
				
				var options = {
					currentPage: cpage,
					totalPages: page,
					alignment: 'right',
					count:data.count,
					selectorId: 'pageSeletct',
					onPageChanged: function(e, oldPage, newPage) {
						dataPage(newPage, keyword,advancedKey);
					}
				};
				$('#paginator').bootstrapPaginator(options);
				$("#pageSeletct").change(function() {
					var page = $("#pageSeletct option:selected").val();
					$('#paginator').bootstrapPaginator("show",page);
				});
				showList(udata.data, cpage, pageSize, data.count);

			},
			error: function(result) {
				alert('error');
			}
		});
	};

	var showList = function(data, cpage, pageSize, count) {
		$('#staffBody').html("");
		if (data == 'none' || data.length == 0) {
			$('#tip').html("<div class='alert alert-warning' style='margin-top:-20px;'>未能搜索到相关员工信息</div>");
			return;
		} else {
			$('#tip').html("");
		}
		$.each(data, function(i, data) {
			var staff = {
				jobNumber: data.jobNumber,
				name: data.name,
				gender: data.gender,
				orgName: data.orgName,
				entryTime: data.entryTime,
				id: data.id,
				job: data.job
			};
			// <td class='center'><label><input type='checkbox' name='check'><span class='lbl'></span></label><td style='display:none'>{{id}}</td></td>
			var model = "<tr><td class='center'>{{jobNumber}}<input type=hidden id=itemId value={{id}}></td><td class='center'>{{name}}</td><td class='center'>{{gender}}</td><td class='center'>{{job}}</td><td class='center'>{{orgName}}</td><td class='center'>{{entryTime}}</td><td class='center'><i id='editIcon' name='editIcon' class='icon-pencil bigger-150'></i>&nbsp;&nbsp;<i id='deleteIcon' name=deleteIcon class='icon-trash  bigger-150'></i></td></tr>";
			var $html = $(Mustache.to_html(model, staff));
			$("#staffBody").append($html);

			//删除事件
			$html.find('#deleteIcon').click({
				html: $html
			}, function(e) {
				var $html = $(e.data.html);
				var id = $html.find("#itemId").val();
				bootbox.confirm("确定删除该员工信息吗？", function(result) {
					if (!result) {
						return;
					} else {
						$.ajax({
							url: '/api/performance/checkAssignmentIdExit?',
							type: 'get',
							data: {'id':id, 'date':date, 'date_next':date_next, '_t':new Date().getTime()},
							success: function(data) {
								// console.info(data);
								if(data == 'false') {
									$.ajax({
										url: '/api/employees/' + id,
										type: 'delete',
										success: function(result) {
											// console.info("result--", result);
											if (result == 'noPrivilege') {
												bootbox.alert('您没有权限,操作失败！');
												return;
											}
											if((count % pageSize) == 1) {
												cpage = cpage - 1;
											}
											dataPage(cpage, "","");
										},
										error: function(result) {
											// console.info(result);
											bootbox.alert("删除员工信息失败！", function() {
												dataPage(cpage, "","");
											});
										}
									});
								}else{
									bootbox.alert('该员工还有未审核的绩效！不能删除！', function() {
										dataPage(cpage, "","");
									});
								}

							}
						});
						// $.get('/api/performance/checkAssignmentIdExit?id=' + id + '&date=' + date + '&date_next=' + date_next, function(data, status) {
						// 	console.info('data', data);
						// 	console.info('status', status);
						// 	if (data == 'false' && status == 'success') {
						// 		$.ajax({
						// 			url: '/api/employees/' + id,
						// 			type: 'delete',
						// 			success: function(result) {
						// 				if (result == 'noPrivilege') {
						// 					bootbox.alert('您没有权限,操作失败！');
						// 					return;
						// 				}
						// 				dataPage(1, "","");
						// 			},
						// 			error: function(result) {
						// 				// console.info(result);
						// 				bootbox.alert("删除员工信息失败！", function() {
						// 					dataPage(1, "","");
						// 				});
						// 			}
						// 		});
						// 	} else {
						// 		bootbox.alert('该员工还有未审核的绩效！不能删除！', function() {
						// 			dataPage(1, "","");
						// 		});
						// 	}
						// });
					}
				});
			});
			//定义编辑按钮编辑事件
			$html.find('#editIcon').click({
				html: $html
			}, function(e) {
				var $html = $(e.data.html);
				var id = $html.find('#itemId').val();
				var cpage = $("#pageSeletct option:selected").val();


				var keys = document.getElementsByName("search_key");
				var keywords = {};
				for (var i = 0; i < keys.length; i++) {
					if (keys[i].checked) {
						keywords.key = keys[i].value;
					}
				}
				if (keywords.key == 1) { //部门
					if ($("#chooseDeptID").val() != "") {
						keywords.value = $("#chooseDeptID").val();
					} else {
						keywords = "";
					}
				} else { //入职时间
					if ($("#from").val() != "" && $("#to").val() != "") {
						if ($("#from").val() > $("#to").val()) {
							keywords = "";
						} else {
							keywords.from = $("#from").val();
							keywords.to = $("#to").val();
						}
					} else {
						keywords = "";
					}
				}

                 if(keywords == "") {
                 	keywords = encodeURIComponent(keywords);
                 }else{
                 	 keywords = encodeURIComponent(JSON.stringify(keywords));
                 }
			
				 
				window.location.href = '/staff/edit?id=' + id + '&cpage=' + cpage + '&keywords=' + keywords;
			});
		});
	};

	var hisPage = $("#hisPage").val();
	var advancedKey = "";
	var keywords = {};
	//填充高级搜索框

	if($("#getKeywords").val() != "" && $("#getKeywords").val() != null && $("#getKeywords").val() != undefined) {
		advancedKey = decodeURIComponent($("#getKeywords").val());
		keywords = JSON.parse(advancedKey);
		// console.info("keywords",keywords);
		if(keywords.key == "1") {
			$("#search_check_depar").attr("checked", "true");
			getParentList(keywords.value);
			$("#chooseDeptID").val(keywords.value);
		}else if(keywords.key == "2") {
			$("#keyword_content").empty();
			$("#keyword_content").append("<input id='from' class='date-picker search_date' name='searchDate'  type='text' data-date-format='yyyy-mm-dd' readonly='true'> 至 <input id='to' class='date-picker search_date' name='searchDate' type='text' data-date-format='yyyy-mm-dd' readonly='true'>");
			$("#search_check_entry").attr("checked", "checked");
			
			$("#from").val(keywords.from);
			$("#to").val(keywords.to);
		}else{
			$("#keyword_content").empty();
			$("#keyword_content").append("<input id='from' class='date-picker search_date' name='searchDate'  type='text' data-date-format='yyyy-mm-dd' readonly='true'> 至 <input id='to' class='date-picker search_date' name='searchDate' type='text' data-date-format='yyyy-mm-dd' readonly='true'>");
			$("#search_check_departure").attr("checked", "true");
			
			$("#from").val(keywords.from);
			$("#to").val(keywords.to);
		}
		$("#custom_search_panel").slideDown();
	}
	// console.info("advancedKey=" , advancedKey);
	if(hisPage == "" || hisPage == 0 || hisPage == null || hisPage == undefined) {
		dataPage(1, "",advancedKey);
	}else{
		dataPage(hisPage, "" ,advancedKey);
	}
	// dataPage(1, "","");


	$('#searchBtn').click(function() {
		var key = document.getElementById("keyword").value + "";
		dataPage(1, key,"");
	});

	var showAlert = function(message, type, delay, callback) {
		$.globalMessenger().post({
			message: message,
			hideAfter: delay,
			type: type,
		});

		if (callback) {
			callback();
		}
	}

	$('#deleteStaffBtn').click(function() {
		var checks = $("input[name='check']");
		// console.info('obj', $("input[name='check']:checked").length);
		var cids = "";
		if ($("input[name='check']:checked").length === 0) {
			showAlert("请选择行！", "error", '3');
			return false;
		}
		bootbox.confirm("确定删除?", function(result) {
			if (!result) {
				return;
			}
			var ids = [];
			$.each(checks, function(index, e) {
				if ($(e).is(":checked")) {
					var cid = $("#table_bug_report tr:eq(" + (index + 1) + ") td:eq(1)").text();;
					ids.push(cid);
				}
			});
			var idData = {
				ids: ids
			};

			// $.ajax({
			// 	url: '/api/employee/del/list',
			// 	type: 'DELETE',
			// 	data: idData,
			// 	success: function(data) {
			// 		$('table th input:checkbox')[0].checked = false;
			// 		if (data) {
			// 			bootbox.alert('删除员工成功！', function() {
			// 				window.location.href = "/staff";
			// 			});
			// 		}

			// 	},
			// 	error: function(result) {
			// 		$('table th input:checkbox')[0].checked = false;
			// 		if (result) {
			// 			bootbox.alert('删除员工失败！', function() {
			// 				window.location.href = "/staff";
			// 			});
			// 		}

			// 	}
			// });
		});
	});
});